﻿using System;
using System.ServiceModel;
using CommunicationDataContract;

namespace CommunicationServiceApplication
{
    public class DesktopApplicationConnection : IDisposable
    {
        #region Private Fields
        private Guid ApplicationId = Guid.Empty;
        private Guid RemoteApplicationId = Guid.Empty;
        private NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
        private EndpointAddress endpoint;
        private IDesktopCommunicationEndPointContract CommunicationEndPoint;
        #endregion

        #region Constructors
        public DesktopApplicationConnection(WindowsServiceController serviceController, Guid remoteApplicationId)
        {
            ApplicationId = serviceController.ApplicationId;
            RemoteApplicationId = remoteApplicationId;
            endpoint = new EndpointAddress(EndpointSettings.GetDesktopApplicationEndpointAddress(RemoteApplicationId));
        }
        #endregion
        #region Methods
        public ApplicationInfo GetApplicationInfo()
        {
            try
            {
                CommunicationEndPoint = ChannelFactory<IDesktopCommunicationEndPointContract>.CreateChannel(binding, endpoint);
                return CommunicationEndPoint.GetInformation(ApplicationId);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public void WindowsServiceStatusChanged(Boolean running)
        {
            try
            {
                CommunicationEndPoint = ChannelFactory<IDesktopCommunicationEndPointContract>.CreateChannel(binding, endpoint);
                CommunicationEndPoint.WindowsServiceStatusChanged(running);
            }
            catch (Exception ex)
            {

            }
        }
        public Boolean Ping()
        {
            try
            {
                 CommunicationEndPoint = ChannelFactory<IDesktopCommunicationEndPointContract>.CreateChannel(binding, endpoint);
                 CommunicationEndPoint.Ping(ApplicationId);
                 return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region IDisposable
        public void Dispose()
        {
            CommunicationEndPoint = null;
        }
        #endregion
    }
}
